import 'package:flutter/material.dart';

class TestKeyboardPage extends StatefulWidget {
  @override
  _TestKeyboardPageState createState() => _TestKeyboardPageState();
}

class _TestKeyboardPageState extends State<TestKeyboardPage> {
  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    _listenKeyboard();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(title: Text("test keyboard")),
      body: Column(
        children: [
          TextField(
            focusNode: _focusNode,
          ),
          RaisedButton(
            onPressed: () {
              bool isFocus = _focusNode.hasFocus;
              if (isFocus) {
                _focusNode.unfocus();
              } else {
                _focusNode.requestFocus();
              }
            },
            child: Text("focus or not focus"),
          ),
          Container(height: 500, color: Colors.red)
        ],
      ),
    );
  }

  void _listenKeyboard() {
    // 这样无法监听到软键盘弹出，除非写在didChangeDependencies里，但这样最好只读，改了之后会重复调用此方法造成不可预期的错误。
    // 监听软键盘最好还是用是否聚焦控制
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      print("addPostFrameCallback");

      // 最好使用这种方式监听软键盘是否弹起，但这样获取不到软键盘高度，因为不在build里获取不到，在didChangeDependencies可以获取到。
      _focusNode.addListener(() {
        bool isFocus = _focusNode.hasFocus;
        print("isFocus == $isFocus");
        if (isFocus) {
          double keyboardHeight = MediaQuery.of(context).viewInsets.bottom;
          print("keyboardHeight == $keyboardHeight");
        }
      });
    });
  }

  @override
  void didChangeDependencies() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      print("addPostFrameCallback in didChangeDependencies");

      if (MediaQuery.of(context).viewInsets.bottom == 0) {
        print("keyboard close");
      } else {
        double keyboardHeight = MediaQuery.of(context).viewInsets.bottom;
        print("keyboard open， and keyboardHeight == $keyboardHeight");
      }
    });
    super.didChangeDependencies();
  }
}
